package com.francis.spring.mvcframework.servlet;

import com.francis.spring.mvcframework.annotation.*;
import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader;
import javafx.beans.binding.ObjectExpression;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author Francis
 * @Date 2020/10/19 22:43
 * @Version 1.0
 */
public class FrancisDispatchServlet extends HttpServlet {
    // 保存application.properties的配置内容
    private Properties  contextConfig = new Properties();
    // 存储所有扫描到的类
    private List<String>  classNames = new ArrayList<String>();
    // IOC容器，保存所有实例化对象，注册式单例模式
    private Map<String, Object> ioc = new HashMap<String, Object>();

    // 保存url和Method的对应关系
    private List<Handler> handlerMapping = new ArrayList<Handler>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req,resp); //开始匹配到对应的方方法
        } catch (Exception e) {
            //如果匹配过程出现异常，将异常信息打印出去
            resp.getWriter().write("500 Exception,Details:\r\n" + Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]", "").replaceAll(",\\s", "\r\n"));
        }
    }
    private void doDispatch(HttpServletRequest req,HttpServletResponse resp) throws Exception{

        try{
            Handler handler = getHandler(req);
            if(handler == null){
                //如果没有匹配上，返回404错误
                resp.getWriter().write("404 Not Found");
                return;
            }
            //获取方法的参数列表
            Class<?> [] paramTypes = handler.method.getParameterTypes();

            //保存所有需要自动赋值的参数值
            Object [] paramValues = new Object[paramTypes.length];
            Map<String,String[]> params = req.getParameterMap();
            for (Map.Entry<String, String[]> param : params.entrySet()) {
                String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
                //如果找到匹配的对象，则开始填充参数值
                if(!handler.paramIndexMapping.containsKey(param.getKey())){continue;}
                int index = handler.paramIndexMapping.get(param.getKey());
                paramValues[index] = convert(paramTypes[index],value);
            }
            //设置方法中的request和response对象
            int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[reqIndex] = req;
            int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[respIndex] = resp;
            handler.method.invoke(handler.controller, paramValues);

        }catch(Exception e){
            throw e;
        }
    }
    private Handler getHandler(HttpServletRequest req) throws Exception{
        if(handlerMapping.isEmpty()){ return null; }

        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");

        for (Handler handler : handlerMapping) {
            try{
                Matcher matcher = handler.pattern.matcher(url);
                //如果没有匹配上继续下一个匹配
                if(!matcher.matches()){ continue; }

                return handler;
            }catch(Exception e){
                throw e;
            }
        }
        return null;
    }
    /**
     * url传过来的参数都是String类型的，HTTP是基于字符串协议
     */
    private Object convert(Class<?> type,String value){
        if(Integer.class == type){
            return Integer.valueOf(value);
        }
        //如果还有double或者其他类型，继续加if
        //这时候，我们应该想到策略模式了
        //在这里暂时不实现，希望小伙伴自己来实现
        return value;
    }

    //初始化
    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1、加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        // 2、扫描相关的类
        doScanner(contextConfig.getProperty("scanPackage"));
        // 3、初始化扫描的类，并且将他们放到IOC容器中
         doInstance();
        // 4、完成依赖注入
         doAutoWried();
        // 5、初始化handlerMapping
        initHandleMapping();
        System.out.println("francis mvcframework is init succcess!");

    }
    /**
     * 扫描相关类
     */
    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/"+scanPackage.replaceAll("\\.","/"));
        File classPath = new File(url.getFile());
        for (File file:classPath.listFiles()) {
            if (file.isDirectory()){
                doScanner(scanPackage+"."+file.getName());
            }else{
                if(!file.getName().endsWith(".class")){ continue; }
                String className = (scanPackage + "." +file.getName()).replaceAll(".class","");
                classNames.add(className);
            }
        }
    }
    /**
     * 初始化HandleMapping
     */
    private void initHandleMapping() {
       if(ioc.isEmpty()){return;}
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(FrancisController.class)){
                continue;
            }
            // 保存写在类上面的@FrancisRequestMapping("/francis")
            String baseUrl = "";
            if(clazz.isAnnotationPresent(FrancisRequestMapping.class)){
                FrancisRequestMapping requestMapping = clazz.getAnnotation(FrancisRequestMapping.class);
                baseUrl = requestMapping.value();
            }
            // 获取所有public方法
            //获取Method的url配置
            Method[] methods = clazz.getMethods();
            for(Method method : methods){
                if(!method.isAnnotationPresent(FrancisRequestMapping.class)){
                    continue;
                }
                FrancisRequestMapping requestMapping = method.getAnnotation(FrancisRequestMapping.class);
                String regex = ("/"+ baseUrl +"/"+requestMapping.value()).replaceAll("/+","/");
                Pattern pattern = Pattern.compile(regex);
                handlerMapping.add(new Handler(pattern,entry.getValue(),method));
                System.out.println("Mapping "+ regex +","+method);
            }
        }


    }
    /**
     *  DI 依赖注入
     */
    private void doAutoWried() {
        if(ioc.isEmpty()){return;}
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            // Declared 所有的特定字段，包括private protected default
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field :fields
                 ) {
                if(!field.isAnnotationPresent(FrancisAutowired.class)){continue;}
                FrancisAutowired autowired = field.getAnnotation(FrancisAutowired.class);
                String beanName = autowired.value().trim();
                if("".equals(beanName)){
                    beanName = field.getType().getName();
                }
                field.setAccessible(true);//强吻
                try {
                    // 注入
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }

    }
    /**
     * IOC过程，工程模式
     */
    private void doInstance() {
        if(classNames.isEmpty()){
            return;
        }
        try {
          for (String className:classNames
             ) {
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(FrancisController.class)
                   ){
                   Object instance = clazz.newInstance() ;
                   // Spring 默认的类名为小写
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName,instance);
                }else if(clazz.isAnnotationPresent(FrancisService.class)){
                    FrancisService service = clazz.getAnnotation(FrancisService.class);
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    if(!"".equals(service.value())){
                           beanName = service.value();
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName,instance);
                    for(Class<?> i : clazz.getInterfaces()){
                        if(ioc.containsKey(i.getName())){
                            throw new Exception("The beanName is exists!");
                        }
                        ioc.put(i.getName(),instance);
                    }
                }

          }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载配置文件
     */
    private void doLoadConfig(String contextConfigLocation) {
        // 直接在类路径下找到Spring的主配置文件，
        InputStream  fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(fis);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis == null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private String toLowerFirstCase(String simpleName) {
        char [] chars = simpleName.toCharArray();
        chars[0] += 32;
        return  String.valueOf(chars);
    }
    /**
     * 记录Controller中的RequestMapping和Method的对应关系
     * 内部类
     */
    private class Handler{

        protected Object controller;	//保存方法对应的实例
        protected Method method;		//保存映射的方法
        protected Pattern pattern;      // 正则url
        protected Map<String,Integer> paramIndexMapping;	//参数顺序

        /**
         * 构造一个Handler基本的参数
         * @param controller
         * @param method
         */
        protected Handler(Pattern pattern,Object controller,Method method){
            this.controller = controller;
            this.method = method;
            this.pattern = pattern;

            paramIndexMapping = new HashMap<String,Integer>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method){

            //提取方法中加了注解的参数
            Annotation[] [] pa = method.getParameterAnnotations();
            for (int i = 0; i < pa.length ; i ++) {
                for(Annotation a : pa[i]){
                    if(a instanceof FrancisRequestParam){
                        String paramName = ((FrancisRequestParam) a).value();
                        if(!"".equals(paramName.trim())){
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }
            }

            //提取方法中的request和response参数
            Class<?> [] paramsTypes = method.getParameterTypes();
            for (int i = 0; i < paramsTypes.length ; i ++) {
                Class<?> type = paramsTypes[i];
                if(type == HttpServletRequest.class ||
                        type == HttpServletResponse.class){
                    paramIndexMapping.put(type.getName(),i);
                }
            }
        }
    }
}
